package com.peng.test.buffertrigger;

import com.github.phantomthief.collection.BufferTrigger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;

/**
 * BufferTriggerSample
 *
 * @author: lupeng6
 * @create: 2023/4/2 11:39
 */
public class BufferTriggerSample {


    @Test
    public void t1() throws InterruptedException {
        BufferTrigger<String> bufferTrigger = BufferTrigger.<String>batchBlocking()
                // 队列最大容量
                .batchSize(5)
                // 每隔n秒消费一次
                .linger(2, TimeUnit.SECONDS)
                // 消费逻辑
                .setConsumerEx((ids) -> {
                    for (String id : ids) {
                        System.out.println(id);
                    }
                })
                .build();

        // 在进程退出的时候主动触发一次 BufferTrigger 消费
        Runtime.getRuntime().addShutdownHook(new Thread(bufferTrigger::manuallyDoTrigger));

        for (int i = 0; i < 4; i++) {
            bufferTrigger.enqueue(i + "");
        }

        Thread.sleep(7000L);
    }


    public void consumer(Map<Long, AtomicInteger> container) {
        System.out.println(container);

        // container.forEach((uid, count) -> System.out.println(Joiner.on("-").join(uid, count.get())));
    }


    @Test
    public void t2() throws InterruptedException {
        BufferTrigger<Long> bufferTrigger = BufferTrigger.<Long, Map<Long, AtomicInteger>> simple()
                .maxBufferCount(10)
                .interval(4, TimeUnit.SECONDS)
                .setContainer(ConcurrentHashMap::new, (map, uid) -> {
                    map.computeIfAbsent(uid, key -> new AtomicInteger()).addAndGet(1);
                    return true;
                })
                .consumer(this::consumer)
                .build();

        // 进程退出时手动消费一次
        Runtime.getRuntime().addShutdownHook(new Thread(() -> bufferTrigger.manuallyDoTrigger()));
        // 最大容量是10，这里尝试添加11个元素0-10
        for (int i = 0; i < 5; i ++) {
            for (long j = 0; j < 11; j ++) {
                bufferTrigger.enqueue(j);
            }
        }

        Thread.sleep(7000);
    }

    @Test
    public void t21() {
        String s = "\001";
        System.out.println(s.toString());
    }


}
